package com.gaowl.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaowl.yygh.commom.exception.HospitalException;
import com.gaowl.yygh.commom.helper.JwtHelper;
import com.gaowl.yygh.commom.result.ResultCodeEnum;
import com.gaowl.yygh.enums.AuthStatusEnum;
import com.gaowl.yygh.model.user.Patient;
import com.gaowl.yygh.model.user.UserInfo;
import com.gaowl.yygh.user.mapper.UserInfoMapper;
import com.gaowl.yygh.user.service.PatientService;
import com.gaowl.yygh.user.service.UserInfoService;
import com.gaowl.yygh.vo.user.LoginVo;
import com.gaowl.yygh.vo.user.UserAuthVo;
import com.gaowl.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    PatientService patientService;

    // 接口1：用户手机号登录
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        // 1.从loginVo获取 输入的手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        // 2.判断手机号和验证码是否为空，空则报错
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }

        // 3.判断手机验证码和输入的验证码是否一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if(!code.equals(redisCode)) {
            throw new HospitalException(ResultCodeEnum.CODE_ERROR);
        }

        //绑定手机号码
        UserInfo userInfo = null;
        System.out.println(loginVo.getOpenid());
        if(!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.selectWxInfoOpenId(loginVo.getOpenid());
            if(null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new HospitalException(ResultCodeEnum.DATA_ERROR);
            }
        }

        //如果userInfo为空，进行正常手机登录
        if(userInfo == null) {
            //判断是否第一次登录：根据手机号查询数据库，如果不存在相同手机号就是第一次登录
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);
            userInfo = baseMapper.selectOne(wrapper);
            if(userInfo == null) { //第一次使用这个手机号登录
                //添加信息到数据库
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }

        //校验是否被禁用
        if(userInfo.getStatus() == 0) {
            throw new HospitalException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        // 如果不是第一次使用该手机号，则直接进行登录；并返回 用户名、token等信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name",name);

        //jwt生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        return map;
    }

    @Override
    public UserInfo selectWxInfoOpenId(String openid) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        return baseMapper.selectOne(queryWrapper);
    }

    //用户认证
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行信息更新
        baseMapper.updateById(userInfo);
    }

    /**
    * @Description: 分页查询用户列表
    * @Author: gaowl@stu.jiangnan.edu.cn
    * @Date: 2021/04/08
    */
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        String name = userInfoQueryVo.getKeyword();   // 用户名称
        Integer status = userInfoQueryVo.getStatus();  // 用户状态（是否已被删除）
        Integer authStatus = userInfoQueryVo.getAuthStatus();   //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();// 开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();    // 结束时间

        // 构建查询条件
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }

        // 调用mapper进行分页查询
        IPage<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        System.out.println(pages.getRecords());

        pages.getRecords().forEach(this::packageUserInfo);
        return pages;
    }

    /**
     * @Description: 封装用户信息
     * @Author: gaowl@stu.jiangnan.edu.cn
     * @Date: 2021/04/08
     */
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus() ==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
    
    /**
    * @Description: 锁定用户
    * @Author: gaowl@stu.jiangnan.edu.cn
    * @Date: 2021/04/08
    */
    @Override
    public void lock(Long userId, Integer status) {
        if(status == 0 || status == 1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }
    }

    /**
     * @Description: 查看用户详情
     * @Author: gaowl@stu.jiangnan.edu.cn
     * @Date: 2021/04/08
     */
    @Override
    public Map<String, Object> show(Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        UserInfo userInfo = baseMapper.selectById(userId);
        map.put("userInfo", userInfo);

        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("patientList", patientList);
        return map;
    }

    /**
    * @Description: 审批用户的认证信息
    * @Author: gaowl@stu.jiangnan.edu.cn
    * @Date: 2021/04/08
    */
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus == 2 || authStatus == -1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }
}
